<!-- 创建工单组件 -->
<template>
  <div style="width: 100%; overflow: hidden">
    <van-calendar
      :show-confirm="false"
      v-model="showDate"
      @confirm="onConfirm"
    />
    <van-calendar
      :show-confirm="false"
      v-model="EndshowDate"
      @confirm="onEndConfirm"
    />
    <van-popup
      v-model="show"
      position="left"
      class="fa"
      :style="{ height: '100%', width: '100%' }"
    >
      <div>
        <!-- 引入公共头部组件 -->
        <HeaderMenu :title="title + '工单'" leftText="返回" />

        <!-- <van-nav-bar
          title="工单"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        /> -->
        <!-- 顶部切换导航栏 -->
        <van-tabs v-model="active">
          <van-tab title="工单信息">
            <van-form @submit="onSubmit">
              <div class="client">
                <van-field
                  label="客户名称："
                  @click="CustomerChoice"
                  right-icon="edit"
                  :rules="[{ required: true, message: '客户不能为空' }]"
                  placeholder="请选择客户"
                  v-model="entity.CustomerName"
                  :disabled="disabled"
                >
                </van-field>
                <!--  clickable -->
                <van-field
                  label="工单类型"
                  placeholder="工单类型"
                  name="picker"
                  :rules="[{ required: true, message: '工单类型不能为空' }]"
                  @click="swoTypeClick"
                  v-model="entity.SWOType"
                  :disabled="disabled"
                />
                <van-popup v-model="showPicker" position="bottom">
                  <van-picker
                    show-toolbar
                    :columns="columns"
                    @confirm="onSWOTypeConfirm"
                    @cancel="showPicker = false"
                  />
                </van-popup>
                <van-field
                  :rules="[{ required: true, message: '样品服务不能为空' }]"
                  :disabled="disabled"
                  @click="sampleChoice"
                  v-if="entity.SWOType == '样品服务'"
                  label="关联单号:"
                  placeholder="关联单号"
                  v-model="entity.RelationNo"
                />
                <van-field
                  :disabled="disabled"
                  label="工单标题"
                  :rules="[{ required: true, message: '工单标题不能为空' }]"
                  placeholder="工单标题"
                  v-model="entity.SWOTitle"
                />
                <van-field
                  :disabled="disabled"
                  @click="timeChangeClick(0)"
                  label="开始日期："
                  placeholder="请选择开始日期"
                  :value="entity.StartTime"
                />
                <van-field
                  :disabled="disabled"
                  @click="timeChangeClick(1)"
                  label="完成日期："
                  placeholder="请选择完成日期"
                  :value="entity.EndTimeRqstd"
                />

                <van-field
                  :disabled="disabled"
                  @click="showClick"
                  label="执行人"
                  :rules="[{ required: true, message: '执行人不能为空' }]"
                  placeholder="执行人"
                  v-model="entity.SalesmanName"
                />
                <!-- <van-popup v-model="showPicker" position="bottom">
                  <van-picker
                    show-toolbar
                    :columns="columns"
                    @confirm="confrim"
                    @cancel="showUser = false"
                  />
                </van-popup> -->
                <van-field
                  label="工单内容"
                  placeholder="工单内容"
                  v-model="entity.SWOContent"
                  :disabled="disabled"
                  autosize
                  rows="10"
                  type="textarea"
                  maxlength="300"
                  show-word-limit
                />
              </div>
              <div v-if="!disabled" class="submitButton">
                <div v-show="hideshow">
                  <van-button round block type="info" native-type="submit"
                    >提交</van-button
                  >
                </div>
              </div>
            </van-form>
          </van-tab>
          <van-tab v-if="title === '查看'" title="回复信息">
            <div class="formalBox">
              <van-list
                :immediate-check="false"
                v-model="swodLoading"
                :finished="swodfinished"
                finished-text="没有更多了"
                @load="onSwodLoading"
              >
                <div
                  class="boxFormal"
                  v-for="(item, index) in SWODList"
                  :key="index"
                >
                  <div class="cardName" style="font-size: 14px">
                    <div class="left">
                      <img src="../../assets/touxiang.png" alt="" />
                    </div>
                    <div class="right">
                      <p style="padding-bottom:5px">{{ item.ExecutorName }}</p>
                      <span >{{ item.CreateTime }}</span>
                      <div style="margin-top:5px">费用金额: ￥{{ momenyFormat(item.ExpenseInfo) }}</div>
                      <div style="margin-top:10px">回复内容:{{ item.FeedbackInfo }}</div>
                    </div>
                  </div>
                </div>
              </van-list>
              <div v-if="SWODList.length==0" style="text-align:center;margin:30px 0">暂无回复记录</div>
            </div>
          </van-tab>
        </van-tabs>
      </div>
      <!-- :close-on-click-overlay="false" -->
      <van-popup
        class="popup"
        position="bottom"
        :style="{ height: '50%', width: '100%' }"
        v-model="showUser"
      >
        <div class="confirmBtn">
          <van-button
            size="mini"
            class="comBtn"
            @click="showUser = false"
            type="danger"
            >取消</van-button
          >
          <van-button size="mini" class="comBtn" @click="confrim" type="info"
            >确认</van-button
          >
        </div>
        <div style="width: 100%; height: calc(100% - 30px); overflow-y: auto">
          <van-list
            :immediate-check="false"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :offset="100"
            @load="onLoad"
          >
            <!-- <p v-for="item in data" :key="item.Id">{{ item.RealName }}</p> -->
            <van-cell
              v-for="item in data"
              :key="item.Id"
              :title="item.RealName"
              @click="cellItem(item)"
              :style="{ background: item.checked ? '#cdcdcd' : '#fff' }"
            />
          </van-list>
        </div>
      </van-popup>
      <Myuser @customerChoice="Client" ref="myuser" />
      <sample @sampleChoice="Clientsample" ref="sample" />
    </van-popup>
  </div>
</template>

<script>
import { Icon } from "vant";
import { Popup } from "vant";
import { AddressList } from "vant";
// 引入公共头部组件
import HeaderMenu from "../../components/VolHeaderMenu.vue";
import {
  Row,
  Col,
  Cell,
  CellGroup,
  Stepper,
  Toast,
  Calendar,
  NavBar,
} from "vant";
import { Field } from "vant";
//客户
import Myuser from "../../components/OwnUser.vue";
import sample from "../../components/sample.vue";

export default {
  props: {
    parentObj: Object,
    // readonly: Boolean
  },
  components: {
    sample,
    "van-stepper": Stepper,
    "van-calendar": Calendar,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    HeaderMenu,
    Myuser,
  },
  data() {
    return {
      // 回复记录是否加载
      swodLoading: false,
      // 回复记录是否加载完成
      swodfinished: false,
      // 显示工单信息  和反馈回复信息 默认显示工单信息
      active: 0,
      // 解决表单输入移动端键盘弹起导致的页面fixed定位元素布局错乱问题
      docmHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      showHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      // 按钮是否禁用
      disabled: false,
      // 导航栏标题  0新增 1修改
      title: "",
      PageRows: 99999,
      readonly: 0,
      finished: false,
      loading: false,
      info: {},
      SWOAList: [],
      showUser: false,
      entity: {},
      data: [],
      showPicker: false,
      show: false,
      showDate: false,
      Id: "",
      EndshowDate: false,
      columns: [],
      // 从工单管理页面 1  跳转的还是我的工单页面 0跳转的
      urlType: 1,
      // 回复记录列表
      SWODList: [],
    };
  },
  created() {
    this.urlType = this.$route.query.urlType;
    // 赋值增删改查类型
    this.readonly = this.$route.query.readonly;
    // 判断是编辑还是查看详情
    if (this.$route.query.readonly == 0) {
      // 新建
      this.title = "新建";
      // 显示提交按钮
      this.disabled = false;
    } else if (this.$route.query.readonly == 1) {
      this.title = "编辑";
      // 编辑
      // 显示提交按钮
      this.disabled = false;
    } else {
      // 查看
      this.title = "查看";
      this.readonly = true;
      this.disabled = true;
    }

    var obj = {
      Id: this.$route.query.Id,
    };
    this.openForm(obj);
  },
  watch: {
    //监听显示高度
    showHeight: function () {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    },
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };
  },
  methods: {
    // 金额千分位格式化
    momenyFormat(num) {
      num = Number(num)
      if (isNaN(num)) return '0.00'
      return num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
    },
    // 回复记录列表
    onSwodLoading() {
      var obj = {
        Id: this.$route.query.Id,
      };
      this.openForm(obj);
    },
    // 工单类型点击事件
    swoTypeClick() {
      // 只有新增和编辑的时候才会弹窗
      if (this.urlType == 0 || this.urlType == 1) {
        this.showPicker = true;
      }
    },
    // 日期选择
    timeChangeClick(item) {
      if (item == 0) {
        this.disabled == true
          ? (this.showDate = false)
          : (this.showDate = true);
      } else {
        this.disabled == true
          ? (this.EndshowDate = false)
          : (this.EndshowDate = true);
      }
    },
    swipeleft() {
      this.show = false;
    },
    touchstart(e) {
      this.startX = e.touches[0].clientX;
      this.startY = e.touches[0].clientY;
    },
    touchmove(e) {
      // this.show = false;
      e.preventDefault();
      this.moveX = e.touches[0].clientX;
      this.moveY = e.touches[0].clientY;
      // this.startX - this.moveX <= 0
      //   ? console.log("你在往右滑")
      //   : console.log("你在往左滑");
    },
    // 创建工单提交
    onSubmit() {
      if (this.readonly == 0) {
        // 新增
        this.http
          .post("/SWOManagement/ServiceWorkOrderMain/SaveData", this.entity)
          .then((resJson) => {
            if (resJson.Success) {
              Toast.success("创建成功!");
              this.show = false;
              this.$router.back();
              // if (this.urlType == 1) {
              //   // 从工单管理页面跳转过来的
              //   // 跳转回工单管理页面
              //   this.$router.push("/workOrder/workOrderManage");
              // } else {
              //   // 从我的工单页面跳转过来的
              //   // 跳转回我的工单页面
              //   this.$router.push("/workOrder/myWorkOrder");
              // }
            } else {
              Toast(resJson.Msg);
              this.$router.back();
            }
          });
      } else {
        // 编辑
        this.http
          .post("/SWOManagement/ServiceWorkOrderMain/UpdateData", this.entity)
          .then((resJson) => {
            if (resJson.Success) {
              Toast.success("编辑成功!");
              this.show = false;
              if (this.urlType == 1) {
                // 从工单管理页面跳转过来的
                // 跳转回工单管理页面
                this.$router.push("/workOrder/workOrderManage");
              } else {
                // 从我的工单页面跳转过来的
                // 跳转回我的工单页面
                this.$router.push("/workOrder/myWorkOrder");
              }
            } else {
              Toast(resJson.Msg);
              if (this.urlType == 1) {
                // 从工单管理页面跳转过来的
                // 跳转回工单管理页面
                this.$router.push("/workOrder/workOrderManage");
              } else {
                // 从我的工单页面跳转过来的
                // 跳转回我的工单页面
                this.$router.push("/workOrder/myWorkOrder");
              }
            }
          });
      }
    },
    Clientsample(Row) {
      console.log(Row);
      this.$set(this.entity, "RelationNo", Row.DocumentNo);
      console.log(this.entity.RelationNo);
      //   this.entity.RelationNo = Row.DocumentNo;
    },
    cellItem(item) {
      this.$set(item, "checked", !item.checked);
      console.log(item.checked);
    },
    showClick() {
      if (this.disabled) {
        this.showUser = false;
        return;
      } else {
        this.showUser = true;
        this.SWOAList = this.SWOAList.map((item) => item.ExecutorName);
        // console.log(this.SWOAList);
        this.data.forEach((item) => {
          this.$set(item, "checked", false);
          // console.log(item);
          let idx = this.SWOAList.findIndex((im) => im == item.RealName);
          // console.log(idx);
          if (idx !== -1) {
            this.$set(item, "checked", true);
          }
        });
      }
    },
    confrim() {
      this.entity.SWOAList = this.data
        .filter((item) => item.checked == true)
        .map((item) => ({ ExecutorId: item.Id, ExecutorName: item.RealName }));

      this.entity.SalesmanId = this.entity.SWOAList.map((item) => {
        return `${item.ExecutorId}-${item.ExecutorName}`;
      });
      this.entity.SalesmanName = this.entity.SWOAList.map(
        (item) => item.ExecutorName
      ).join(",");
      this.showUser = false;
    },
    onLoad() {
      this.PageRows += 5;
      this.getUserData();
      // this.loading = false;
    },
    formatDate(date) {
      var time = new Date(date);
      var y = time.getFullYear();

      return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    formatEndDate(date) {
      var time = new Date(date);
      var y = time.getFullYear();

      return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onSWOTypeConfirm(value) {
      this.entity.SWOType = value;
      this.showPicker = false;
    },
    getSelsct() {
      this.http
        .post("/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey", {
          Condition: "DicKey",
          Keyword: "WorkOrderType",
        })
        .then((res) => {
          this.columns = res.Data.DictionaryDetailsList;
          console.log(this.columns);

          if (this.columns.length > 0) {
            this.columns = this.columns.map((item) => {
              return item.DicName;
            });
          }
          console.log(this.columns);
        });
    },
    onConfirm(date) {
      this.showDate = false;
      this.entity.StartTime = this.formatDate(date);
    },
    onEndConfirm(date) {
      this.EndshowDate = false;
      this.entity.EndTimeRqstd = this.formatEndDate(date);
    },
    //返回
    // onClickLeft() {
    //   this.show = false;
    //   this.$router.go(-1);
    // },
    //选中的产品

    //关闭
    close() {
      this.show = false;
    },
    //本条客户的数据
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);

      this.entity.CustomerId = a.Id || a.cCusCode;
    },
    //选择客户
    CustomerChoice() {
      console.log(this.readonly);
      if (!this.readonly) this.$refs.myuser.openForm();
    },
    sampleChoice() {
      // 不是查看的条件下弹窗
      if (this.urlType == 0 || this.urlType == 1) {
        this.$refs.sample.openForm();
      }
    },
    getDataList() {
      this.http
        .post("/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll", {
          SortField: "Id",
          SortType: "desc",
          Search: {
            Condition: "Id",
            Keyword: this.Id,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.Success) {
            this.entity = res.Data;

            this.$set(
              this.entity,
              "CreateTime",
              this.entity.CreateTime.substring(0, 10)
            );
          } else {
            Toast(res.Msg);
          }
        });
    },
    getUserData() {
      this.http
        .post("/Base_Manage/Base_User/GetDataList", {
          PageIndex: 1,
          PageRows: this.PageRows,
          SortField: "CreateTime",
          SortType: "desc",
          Search: {},
        })
        .then((resJson) => {
          this.data = resJson.Data;
          this.loading = false;
          if (this.data.length >= resJson.Total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
        });
    },
    init() {
      this.Id = "";
      this.show = true;
      (this.data = []), (this.entity = {});
    },
    op() {
      this.http.post("/Base_Manage/Home/GetOperatorInfo").then((resJson) => {
        if (resJson.Success) {
          this.info = resJson.Data.UserInfo;
        } else {
          Toast(resJson.Msg);
        }
      });
    },
    //  获取工单详情数据
    openForm(item) {
      this.init();
      this.getSelsct();
      this.op();
      this.getUserData();
      if (item.Id) {
        this.http
          .post("/SWOManagement/ServiceWorkOrderMain/GetTheDataForDetail", {
            id: item.Id,
          })
          .then((resJson) => {
            this.loading = false;

            this.entity = resJson.Data;
            // 回复记录列表
            this.SWODList = resJson.Data.SWODList;
            console.log("回复记录", this.SWODList);
            if (this.entity.StartTime) {
              this.$set(
                this.entity,
                "StartTime",
                this.entity.StartTime.substring(0, 10)
              );
            }

            if (this.entity.EndTimeRqstd) {
              this.$set(
                this.entity,
                "EndTimeRqstd",
                this.entity.EndTimeRqstd.substring(0, 10)
              );
            }
            if (this.entity.SWOAList && this.entity.SWOAList.length > 0) {
              this.SWOAList = this.entity.SWOAList;
              // this.entity.SalesmanId = this.entity.SWOAList.map((item) => item.ExecutorId + '-' + item.ExecutorName)
              this.$set(
                this.entity,
                "SalesmanName",
                this.entity.SWOAList.map((item) => item.ExecutorName).join(",")
              );
            }
          });
      }
    },
  },
};
</script>

<style scoped>
.cardName{
  margin: 20px 10px;
  padding-bottom: 15px;
  display:flex;
  box-shadow: 0 15px 30px  rgba(0, 0, 0, .4);
  border-radius: 10px;
}
.left{
  flex:1;
}
.right{
  padding-left: 10px;
  padding-top:15px;
  flex:9

}
.Fa {
  display: flex;
  justify-content: left;
}
.left {
  margin: 10px 0px 10px 15px;
}
.fontstepper {
  margin-left: 15px;
  line-height: 40px;
}
.font {
  margin-left: 15px;
  font-size: 18px;
}
.aa {
  text-align: right;
}
.scrollBar {
  /* height: 550px; */
  height: calc(100vh - 220px);
  /* padding-bottom: 80px; */
  overflow: auto;
}
.close {
  position: "absolute";

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}
.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.mysamplebox {
  width: 95%;

  margin: 0 auto;

  border: 1px solid #ccc;
  /* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

  margin-top: 20px;
  margin-bottom: 10px;
}
.confirmBtn {
  /* position: fixed; */
  /* top: 50%; */
  width: 100%;
  height: 44px;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  line-height: 2;
  background-color: #fff;
  box-sizing: border-box;
  z-index: 100;
  border-radius: 20px 20px 0 0;
}
.comBtn {
  border-radius: 4px;
  margin-top: 5px;
}
</style>
